import "reflect-metadata";
import { createConnection } from "typeorm";
import { NextFunction, Request, Response } from "express";
import { JWT_SECRET } from './utils/constants';
import * as express from "express";
import * as bodyParser from "body-parser";
import * as cors from 'cors';

import userRouter from './router/user';
import readerRouter from './router/reader';
import borrowRouter from './router/borrow';
import bookRouter from './router/book'

import expressJwt = require('express-jwt')

createConnection().then(async connection => {
  // 创建实例
  const app = express();

  // 挂载中间件
  app.use(bodyParser.json());
  app.use(bodyParser());
  app.use(cors());
  // 封装一个便于响应错误结果的中间件
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.error = (msg: string) => {
      return res.send({ code: 400, msg });
    }
    next();
  })
  // 封装一个便于响应查询成功数据的中间件
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.success = (data: any, msg: string = '查询成功！',) => {
      return res.send({ code: 200, msg, data });
    }
    next();
  })
  // 封装一个便于响应查询成功信息的中间件
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.successMsg = (msg: string = '查询成功！') => {
      return res.send({ code: 200, msg });
    }
    next();
  })
  // 在路由之前，配置解析 Token 的中间件
  app.use(expressJwt({ secret: JWT_SECRET, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }))

  // 挂载路由
  app.use(userRouter);
  app.use(readerRouter);
  app.use(borrowRouter);
  app.use('/book', bookRouter);

  // 定义错误的中间件
  app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
    // token 错误
    if (err.name === 'UnauthorizedError') return res.error('身份认证失败！')
  })

  // 开启服务
  app.listen(3000, () => {
    console.log("Express server running at http://localhost:3000");
  });

}).catch(error => console.log(error));
